package com.dc.base.utils;

import javax.servlet.http.HttpServletRequest;

public class RequestUtil {

    /**
     * 单例模式
     */
    private static volatile RequestUtil INSTANCE;
    private RequestUtil() {}

    public static RequestUtil getInstance() {
        synchronized (RequestUtil.class){
            if (INSTANCE == null) {
                INSTANCE = new RequestUtil();
            }
            return INSTANCE;
        }
    }

    /**
     * 获取请求ip信息
     * @param request HttpServletRequest对象
     * @return
     */
    public String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.contains(",")) {
            ip = ip.split(",")[0];
        }
        ip = ip.replace("0:0:0:0:0:0:0:1", "127.0.0.1");
        return ip;
    }

}
